#ifndef NET_TCP_SESSION_H
#define NET_TCP_SESSION_H

#include "../../../Base/Threaded.h"
#include "../../../Base/RecursiveLockingMutex.h"
#include "../../../Base/Pause.h"
#include "TcpPacket.h"
#include <boost/asio.hpp>

#ifdef _WIN32
#include <conio.h>
#else
#include "../common/conio.h"
#endif

#define MPN_TCP_MTX_LOCK_DELAY		1
#define MPN_TCP_DEF_SOCKET_MAX		8
#define MPN_TCP_SESSION_NO_ID		254
#define MPN_TCP_DEF_PORT			2145

using namespace mp_base;
using boost::asio::ip::tcp;
using mp_base::Pause;

namespace mp_net
{
	typedef boost::shared_ptr<boost::asio::io_service>	spIoService;
	typedef unsigned int uint;
	typedef unsigned char byte;
	/*
	* @class	TcpSession
	* @brief	Represents a connection from here to another endpoint	
	*
	*/
	class TcpSession : 
		public Threaded, public RecursiveLockingMutex
	{
	public:
		
		/* ## Constructor, Initialization, and Destructor  ## */

		TcpSession(const uint maxSockets=MPN_TCP_DEF_SOCKET_MAX);
		virtual ~TcpSession();
		
		virtual void SetIoService(spIoService ioService);

		/* ## Threaded Methods ## */

		virtual void ThreadInitialization();
		virtual void ThreadUpdate();
		virtual void ThreadShutdown();

		/* ## Socket Thread Methods ## */

		void AsyncSendProc(const boost::system::error_code& error,
                     std::size_t nBytesTransferred, byte index);
		void AsyncReceiveProc(const boost::system::error_code& error,
					byte index);

	protected:
		
		void AsyncReceive();
		void AsyncSend();

		void UpdateSockets();
		bool AddSocket(tcp::socket* socket);
		void RemoveSocket(tcp::socket* socket);
		
		//Packets
		TcpPacket**		m_outPacket;
		TcpPacket**		m_inPacket;
		// Sockets
		tcp::socket**	m_socket;		//BB
		byte			m_socketCount;
		byte			m_maxSockets;	
		byte			m_socketIndex;
		//IO Service
		spIoService		m_ioService;
		//Identification
		byte			m_SessionID;
		byte*			m_connectedSessions;
	};
}
#endif